package com.func.domain.award.service.distribute.impl;

import com.func.domain.award.model.aggregate.GiveOutPrizesAggregate;
import com.func.domain.award.model.entity.DistributeAwardEntity;
import com.func.domain.award.model.entity.UserAwardRecordEntity;
import com.func.domain.award.model.entity.UserCreditAwardEntity;
import com.func.domain.award.model.valobj.AwardStateVO;
import com.func.domain.award.repository.IAwardRepository;
import com.func.domain.award.service.distribute.IDistributeAward;
import com.func.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;

/**
 * <p>
 * UserCreditRandomAward
 * </p>
 *
 * @author Simon
 * @version 2025.03.20.1.0.0
 * @description 用户积分奖品, 支持 award_config 透传, 满足黑名单积分奖励
 * @since 2025-03-20
 */

@Slf4j
@Component("user_credit_random")
public class UserCreditRandomAward implements IDistributeAward {
    @Resource
    private IAwardRepository awardRepository;
    @Override
    public void giveOutPrizes(DistributeAwardEntity distributeAwardEntity) {
        // 奖品ID
        Integer awardId = distributeAwardEntity.getAwardId();
        // 优先走外部透传
        String awardConfig = distributeAwardEntity.getAwardConfig();
        if (null == awardConfig) {
            awardConfig = awardRepository.queryAwardConfig(awardId);
        }
        String[] creditRange = awardConfig.split(Constants.SPLIT);
        if (creditRange.length != 2) {
            throw new RuntimeException("award_config " + awardConfig + " 配置不是一个范围值, 如1, 100");
        }

        // 生成随机积分值
        BigDecimal creditAmount = generateRandom(new BigDecimal(creditRange[0]), new BigDecimal(creditRange[1]));

        // 组合成聚合对象
        UserAwardRecordEntity userAwardRecordEntity = GiveOutPrizesAggregate.buiDistributeUserAwardRecordEntity(distributeAwardEntity.getUserId(),
                distributeAwardEntity.getOrderId(), awardId, AwardStateVO.create);

        UserCreditAwardEntity userCreditAwardEntity = GiveOutPrizesAggregate.buildUserCreditAwardEntity(distributeAwardEntity.getUserId(), creditAmount);

        GiveOutPrizesAggregate giveOutPrizesAggregate = GiveOutPrizesAggregate.builder()
                .userAwardRecordEntity(userAwardRecordEntity)
                .userCreditAwardEntity(userCreditAwardEntity)
                .userId(distributeAwardEntity.getUserId())
                .build();

        // 存储聚合对象
        awardRepository.saveGiveOutPrizesAggregate(giveOutPrizesAggregate);
    }

    private BigDecimal generateRandom(BigDecimal min, BigDecimal max) {
        BigDecimal randomBigDecimal = min.add(BigDecimal.valueOf(Math.random()).multiply(max.subtract(min)));
        return randomBigDecimal.round(new MathContext(3));
    }
}
